<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\api\controller\Cloudcomputing;
use app\common\controller\Backend;
use app\common\func\Tools;
use app\common\model\BalanceType;
use app\common\model\Company;
use app\common\model\WithdrawalChannel;

/**
 * 提现订单管理
 *
 * @icon fa fa-circle-o
 */
class WithdrawalOrder extends Backend
{

    /**
     * WithdrawalOrder模型对象
     * @var \app\common\model\WithdrawalOrder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\WithdrawalOrder;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['company', 'user', 'type'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->clearing_form = ($row->clearing_form == 1) ? '秒结算' : '月结算';
                $row->getRelation('company')->visible(['name']);
                $row->getRelation('user')->visible(['nickname']);
                $row->getRelation('type')->visible(['name']);
                $row->withdrawal_channel_id = ($row->withdrawal_channel_id > 0) ? WithdrawalChannel::where('id', $row->withdrawal_channel_id)->value('name') : '未设置';
                switch ($row->payment_status) {
                    case 1:
                        $row->payment_status_text = '代付中';
                        break;
                    case 2:
                        $row->payment_status_text = '代付成功';
                        break;
                    case 3:
                        $row->payment_status_text = '代付失败';
                        break;
                }
                switch ($row->audit_status) {
                    case 1:
                        $row->audit_status_text = '待审核';
                        break;
                    case 2:
                        $row->audit_status_text = '已审核';
                        break;
                    default:
                        $row->audit_status_text = '待审核';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 审核订单
     */
    public function orderaudit()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isPost()) {
            $ids = $this->request->post('ids');
            if (!empty($ids)) {
                $ids = implode(",", json_decode($ids));
                $success = 0;
                $count = 0;
                // 获取提现通道
                $withdrawal_channel = WithdrawalChannel::where('status', 1)->find();
                if (!empty($withdrawal_channel)) {
                    $cloudcomputingData = [
                        "enterprise_code" => $withdrawal_channel->enterprise_code,
                        "channel_code" => $withdrawal_channel->channel_code,
                        "task_code" => $withdrawal_channel->task_code,
                        "public_key" => $withdrawal_channel->public_key
                    ];
                    $order = $this->model::where(['id' => ['in', $ids]])->select();
                    $count = count($order);
                    foreach ($order as $row) {
                        if ($row->status == 1 && $row->payment_status == 1 && $row->audit_status == 1) {
                            if ($this->model::where('order_number', $row->order_number)->update(["withdrawal_channel_id" => $withdrawal_channel["id"],"audit_status" => 2, "audit_time" => time()])) {
                                $return = Cloudcomputing::singleWithdrawal($row->order_number, $cloudcomputingData);
                                if ($return["code"] == 200) {
                                    $success++;
                                    $this->model::where('order_number', $row->order_number)->update(["payment_status" => 3, "remarks" => $return["msg"]]);
                                }
                            }
                        }
                    }
                    $this->success("审核成功【" . $success . "】，审核失败【" . ($count - $success) . "】！");
                } else {
                    $this->error("请先设置提现通道！");
                }
            } else {
                $this->error("请选择要审核的数据！");
            }
        }
    }

    /**
     * 订单作废
     */
    public function ordervoid($ids)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isPost()) {
            if (!empty($ids)) {
                $order = $this->model::where('id', $ids)->find();
                if (!empty($order)) {
                    if ($order->status != 1) {
                        $this->error("该订单状态错误！");
                    }
                    if ($order->payment_status == 2) {
                        $this->error("该订单已完成，无法作废！");
                    }
                    $res = $this->model::where('order_number', $order->order_number)->update(["status" => 2]);
                    if ($res) {
                        // 提现余额返还
                        if (Tools::saveBalance($order->main_type, $order->sale_id, $order->withdrawal_money, 2)) {
                            $this->success("操作成功！");
                        } else {
                            $this->model::where('order_number', $order->order_number)->update(["status" => 1]);
                            $this->error("操作失败，请重新操作");
                        }
                    } else {
                        $this->error("操作失败");
                    }
                } else {
                    $this->error("订单信息错误");
                }
            } else {
                $this->error("参数错误");
            }
        }
    }

    /**
     * 详情
     */
    public function detail($ids)
    {
        $info = $this->model::where('id', $ids)->find();
        $info->company = Company::where('id', $info->company_id)->value('name');
        $info->sales = User::where('id', $info->sale_id)->value('nickname');
        if ($info->withdrawal_channel_id > 0) {
            $info->withdrawal_channel = WithdrawalChannel::where('id', $info->withdrawal_channel_id)->value('name');
        } else {
            $info->withdrawal_channel = "未设置";
        }
        $info->balance_type = BalanceType::where('id', $info->balance_type_id)->value('name');
        $info->clearing_form = ($info->clearing_form == 1) ? '秒结算' : '月结算';
        $info->state_text = ($info->status == 1) ? '正常' : '已作废';
        $info->audit_status_text = ($info->audit_status == 1) ? '待审核' : '已审核';
        switch ($info->payment_status) {
            case 1:
                $info->payment_status_text = '代付中';
                break;
            case 2:
                $info->payment_status_text = '代付成功';
                break;
            case 3:
                $info->payment_status_text = '代付失败';
                break;
        }
        $this->view->assign("info", $info);
        return $this->view->fetch();
    }
}
